package com.FrameWork.Utils;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Random;

import com.FrameWork.Common.MyApplication;
import com.SFA.Main.HttpFactory;

import org.apache.http.client.ClientProtocolException;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.sqlite.SQLiteCursor;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.PixelFormat;
import android.graphics.PorterDuff.Mode;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.drawable.Drawable;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Environment;
import android.os.StatFs;

@SuppressLint("SdCardPath")
public class Utils {
	//public final static String DIR = Environment.getExternalStorageDirectory()+ "/SFA";
	public final static String DIR = "/sdcard/SFA";
	public final static String ImageFolder = "IMAGES";

	private static int FREE_SD_SPACE_NEEDED_TO_CACHE = 1;

	public static String BuildFilePath(String url) {
		String LOCALURL = url;// URLEncoder.encode(url);
		return DIR + "/" + LOCALURL;
	}

	public static String getId(String datetime) {
		return datetime + (int) (Math.random() * 10000)
				+ (int) (Math.random() * 10000);
	}

	/**
	 * 检查存储卡是否插入
	 * 
	 * @return
	 */
	public static boolean checkIsHasSdcard() {
		String status = Environment.getExternalStorageState();
		if (status.equals(Environment.MEDIA_MOUNTED)) {
			return true;
		} else {
			return false;
		}
	}

	/**
	 * 获取缩略图并转向
	 * 
	 * @param bitmap
	 * @return
	 *//*
	public static Bitmap extractThumbnail(Bitmap bitmap) {
		int oldWidth = bitmap.getWidth();
		int oldHight = bitmap.getHeight();
		int newWidth = 500;
		int newHeight = newWidth * oldHight / oldWidth;
		bitmap = ThumbnailUtils.extractThumbnail(bitmap, newWidth, newHeight);
		return bitmap;
	}

	public static Bitmap extractThumbnail(Bitmap bitmap,int ViewHeight) {
		int oldWidth = bitmap.getWidth();
		int oldHight = bitmap.getHeight();
		int newWidth = ViewHeight;
		int newHeight = newWidth * oldHight / oldWidth;
		bitmap = ThumbnailUtils.extractThumbnail(bitmap, newWidth, newHeight);
		return bitmap;
	}*/

	public static boolean checkNetworkIsAvailable(Activity activity) {
		ConnectivityManager manager = (ConnectivityManager) activity
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo networkinfo = manager.getActiveNetworkInfo();
		if (networkinfo == null || !networkinfo.isAvailable()
				|| !networkinfo.isConnected())
			return false;
		else
			return true;
	}

	public static Bitmap drawableToBitmap(Drawable drawable) {

		Bitmap bitmap = Bitmap
				.createBitmap(
						drawable.getIntrinsicWidth(),
						drawable.getIntrinsicHeight(),
						drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888
								: Bitmap.Config.RGB_565);
		Canvas canvas = new Canvas(bitmap);
		// canvas.setBitmap(bitmap);
		drawable.setBounds(0, 0, drawable.getIntrinsicWidth(),
				drawable.getIntrinsicHeight());
		drawable.draw(canvas);
		return bitmap;
	}

	public static boolean Exist(String url) {
		File file = new File(url);
		return file.exists();

	}

	public static void exit() {
		int pid = android.os.Process.myPid();
		android.os.Process.killProcess(pid); // 结束当前进程
	}

	public static Bitmap GetBitmap(String url, int quantity)
			throws ClientProtocolException {
		Bitmap map = null;
		if (url == null || url.length() == 0)
			return null;
		String filename = "";
		try {
			filename = url.substring(url.indexOf("+") + 1);
		} catch (Exception err) {
		}

		String LOCALURL = Utils.GetStringForMD5(filename);// URLEncoder.encode(filename);
		if (Exist(DIR + "/" + LOCALURL)) {
			map = BitmapFactory.decodeFile(DIR + "/" + LOCALURL);

		} else {
			try {
				// url = URLEncoder.encode(url, "UTF-8");
				map = HttpFactory.HttpFactorys.GetInputStream(url);
				if (map != null) {
					saveBmpToSd(map, LOCALURL, quantity);
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return map;
	}

	/***
	 * 产生一个10以内的随机整数
	 */
	public static int getRandom() {
		return new Random().nextInt(20) + 1;
	}

	/**
	 * 返回以最高(maxHeight)同比例缩放后的Bitmap对象。
	 * 
	 */
	public static Bitmap getResizedImage(String imagePath, int maxHeight) {
		BitmapFactory.Options options = new BitmapFactory.Options();
		options.inJustDecodeBounds = true;

		// 获取这个图片的宽和高
		Bitmap bitmap = BitmapFactory.decodeFile(imagePath, options); // 此时返回bm为空
		// 计算缩放比
		options.inSampleSize = computeSampleSize(options, -1, maxHeight
				* maxHeight);
		// 重新读入图片，注意这次要把options.inJustDecodeBounds 设为 false
		options.inJustDecodeBounds = false;
		bitmap = BitmapFactory.decodeFile(imagePath, options);
		return bitmap;
	}

	public static int computeSampleSize(BitmapFactory.Options options,
			int minSideLength, int maxNumOfPixels) {
		int initialSize = computeInitialSampleSize(options, minSideLength,
				maxNumOfPixels);
		int roundedSize;
		if (initialSize <= 8) {
			roundedSize = 1;
			while (roundedSize < initialSize) {
				roundedSize <<= 1;
			}
		} else {
			roundedSize = (initialSize + 7) / 8 * 8;
		}
		return roundedSize;
	}

	private static int computeInitialSampleSize(BitmapFactory.Options options,
			int minSideLength, int maxNumOfPixels) {
		double w = options.outWidth;
		double h = options.outHeight;

		int lowerBound = (maxNumOfPixels == -1) ? 1 : (int) Math.ceil(Math
				.sqrt(w * h / maxNumOfPixels));
		int upperBound = (minSideLength == -1) ? 128 : (int) Math.min(
				Math.floor(w / minSideLength), Math.floor(h / minSideLength));

		if (upperBound < lowerBound) {
			// return the larger one when there is no overlapping zone.
			return lowerBound;
		}

		if ((maxNumOfPixels == -1) && (minSideLength == -1)) {
			return 1;
		} else if (minSideLength == -1) {
			return lowerBound;
		} else {
			return upperBound;
		}

	}

	/**
	 * MD5 加密
	 */
	public static String GetStringForMD5(String str) {
		MessageDigest messageDigest = null;

		try {
			messageDigest = MessageDigest.getInstance("MD5");

			messageDigest.reset();

			messageDigest.update(str.getBytes("UTF-8"));
		} catch (NoSuchAlgorithmException e) {
			System.out.println("NoSuchAlgorithmException caught!");
			System.exit(-1);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}

		byte[] byteArray = messageDigest.digest();

		StringBuffer md5StrBuff = new StringBuffer();

		for (int i = 0; i < byteArray.length; i++) {
			if (Integer.toHexString(0xFF & byteArray[i]).length() == 1)
				md5StrBuff.append("0").append(
						Integer.toHexString(0xFF & byteArray[i]));
			else
				md5StrBuff.append(Integer.toHexString(0xFF & byteArray[i]));
		}

		return md5StrBuff.toString().toUpperCase();
	}

	/**
	 * 在TemplateHTML中包含了特有的%s标明了插入位置。
	 * 
	 * @author Steven Jiang
	 * @param resId
	 *            HtmlPath_Template的资源ID。
	 * @param owner
	 *            需要从Activity调用getAssets()
	 * @return
	 */
	public static String getTemplateHTML(int resId, Context owner) {
		// 拼凑出需要显示的菜单内容
		InputStream stream = null;
		int length = 0;

		byte[] maindata = new byte[1024 * 10];
		try {
			stream = owner.getAssets().open(owner.getString(resId));
			length = stream.read(maindata);
		} catch (IOException e1) {
			e1.printStackTrace();
		} finally {
			if (stream != null) {
				try {
					stream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
				stream = null;
			}
		}
		String template = new String(maindata, 0, length);
		return template;
	}

	/**
	 * 获取内嵌在Asset里面的文件路径。
	 * 
	 * @param resId
	 * @param owner
	 * @return
	 */
	public static String getTemplateFilePath(String path) {
		String TempHtmlPath = "file:///android_asset/";
		TempHtmlPath += path;
		return TempHtmlPath;
	}

	/**
	 * 拨打电话的功能。
	 */
	public static void makeCall(Activity owner, String phoneNumber) {
		Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:"
				+ phoneNumber));
		// 开始处理意图 执行
		owner.startActivity(intent);
		((Activity)owner).overridePendingTransition(android.R.anim.slide_in_left,android.R.anim.slide_out_right);
	}

	/***
	 * 
	 * @param inputStream
	 * @return 把流转化为字符串
	 * @throws Exception
	 */
	public static String readContents(InputStream inputStream) throws Exception {
		BufferedReader in = null;
		StringBuffer sb = new StringBuffer();
		in = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));

		String inputLine;
		while ((inputLine = in.readLine()) != null) {
			sb.append(inputLine);
			sb.append("\n");
		}
		return sb.toString();
	}

	public static void saveBmpToSd(Bitmap bm, String url, int quantity) {
		saveBmpToSd(bm, url, CompressFormat.PNG, quantity);
	}

	public static String saveBmpToSd(Bitmap bm, String url,
			CompressFormat format, int quantity) {

		if (bm == null) {
			return null;
		}
		// 判断sdcard上的空间
		if (FREE_SD_SPACE_NEEDED_TO_CACHE > freeSpaceOnSd()) {
			return null;
		}
		if (!Environment.MEDIA_MOUNTED.equals(Environment
				.getExternalStorageState()))
			return null;
		String filename = url;
		// 目录不存在就创建

		File file = null;
		if (!url.contains(DIR))
			file = new File(DIR + "/" + filename);
		else
			file = new File(url);

		if (!file.getParentFile().exists())
			file.getParentFile().mkdirs();

		try {
			file.createNewFile();
			OutputStream outStream = new FileOutputStream(file);
			bm.compress(format, quantity, outStream);
			outStream.flush();
			outStream.close();

		} catch (FileNotFoundException e) {

		} catch (IOException e) {
			e.printStackTrace();
		}
		return file.toURI().toString();
	}

	/**
	 * 将运行时拼接好的HTML文件保存到getFilesDir()中。
	 * 
	 * @author Steven Jiang
	 * @param htmlDocument
	 *            拼接好的HTML文档
	 * @param owner
	 *            需要从Activity调用getFilesDir()
	 * @param fileName
	 *            保存的文件名，一般用当前类的TAG充当。
	 * @return 保存成功返回文件的完整路径toURL()。
	 */
	public static String saveRuntimeHTML(String htmlDocument, Context owner,
			String fileName) {
		// 创建文件，用类名做名称。
		File tempFile = new File(String.format("%s/%s.html",
				owner.getFilesDir(), fileName));

		FileOutputStream outputstream = null;
		try {
			// 创建文件输出流
			// outputstream = this.openFileOutput("test.html",
			// Context.MODE_PRIVATE);
			outputstream = new FileOutputStream(tempFile);

			// 将二进制文件输出
			outputstream.write(htmlDocument.getBytes());

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			// 关闭
			try {
				outputstream.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
			outputstream = null;
		}

		try {
			return tempFile.toURL().toString();
		} catch (MalformedURLException e1) {
			e1.printStackTrace();
			return null;
		}
	}

	/***
	 * 保存文件至SD卡
	 * 
	 * @param bm
	 * @param url
	 * @param quantity
	 */
	public static String savFilepToSd(InputStream inputStream, String file_name) {

		if (inputStream == null || FREE_SD_SPACE_NEEDED_TO_CACHE > freeSpaceOnSd() || !Environment.MEDIA_MOUNTED.equals(Environment
				.getExternalStorageState()))
			return null;
		String filename = file_name;
		// 目录不存在就创建
		File dirPath = new File(DIR);
		if (!dirPath.exists()) {
			dirPath.mkdir();
		}
		dirPath = new File(DIR + "/" + ImageFolder + "/");
		if (!dirPath.exists()) {
			dirPath.mkdir();
		}

		filename = dirPath.getPath() + "/" + filename;
		File file = new File(filename);
		OutputStream outStream = null;
		try {
			file.createNewFile();
			outStream= new FileOutputStream(file);

			byte buf[] = new byte[1280];
			int byteRead = -1;
			while ((byteRead = (inputStream.read(buf))) != -1) {
				outStream.write(buf, 0, byteRead);
			}
			outStream.flush();

			
		} catch (Exception e) {
			e.printStackTrace();
			filename= null;
		}finally
		{
			if(outStream != null)
			{
				try {
					outStream.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				outStream = null;
			}
		}
		return filename;

	}

	public static Bitmap toRoundCorner(Bitmap bitmap, int pixels) {
		Bitmap output = Bitmap.createBitmap(bitmap.getWidth(),
				bitmap.getHeight(), Config.ARGB_8888);
		Canvas canvas = new Canvas(output);
		final int color = 0xff424242;
		final Paint paint = new Paint();
		final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
		final RectF rectF = new RectF(rect);
		final float roundPx = pixels;
		paint.setAntiAlias(true);
		canvas.drawARGB(0, 0, 0, 0);
		paint.setColor(color);
		canvas.drawRoundRect(rectF, roundPx, roundPx, paint);
		paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
		canvas.drawBitmap(bitmap, rect, rect, paint);
		return output;
	}

	/**
	 * 计算sdcard上的剩余空间
	 */
	private static int freeSpaceOnSd() {
		StatFs stat = new StatFs(Environment.getExternalStorageDirectory()
				.getPath());
		double sdFreeMB = ((double) stat.getAvailableBlocks() * (double) stat
				.getBlockSize()) / 1024 * 1024;// MB

		return (int) sdFreeMB;
	}

	/**
	 * 判断sdCard的状态
	 * @return
	 * 		true:存在
	 * 		false:不存在
	 */
	public static boolean sdCardIsExsit(){ 
		return Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED); 
	}


	/**
	 * 通过byte[]数组转化为Bitmap。
	 */
	public static Bitmap   getBitmapFromByte(byte[] bytes){
		BitmapFactory.Options options = new BitmapFactory.Options();
		options.inJustDecodeBounds = true;

		// 获取这个图片的宽和高
		Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0,bytes.length,options); // 此时返回bm为空
		// 计算缩放比
		options.inSampleSize = computeSampleSize(options, -1, 80
				* 80);
		// 重新读入图片，注意这次要把options.inJustDecodeBounds 设为 false
		options.inJustDecodeBounds = false;
		bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length, options);

		return bitmap;

	}
	/**
	 * bitmap转化为byte数组
	 * @param bitmap
	 * @return
	 */
	public static byte[] getBytesFrom(Bitmap bitmap){
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
		return  baos.toByteArray();

	}
	public static Object[] getBitmapFormPhotoId(String photoId){
		String sql=String.format("select * from PHOTO where id=\'%1$s\'",photoId);
		Object[] obj=new Object[3];
		SQLiteCursor cursor=null;
		try
		{
			cursor=MyApplication.getInstance().DataProvider.Query(sql);
			if (cursor.moveToFirst()) {
				obj[0]=cursor.getString(cursor.getColumnIndex("ID"));
				obj[1] = cursor.getBlob(cursor.getColumnIndex("PHOTO_BLOB"));
				obj[2]=cursor.getString(cursor.getColumnIndex("PHOTO_TYPE_ID"));
			}
		}
		catch(Exception err)
		{

		}
		finally
		{
			if (cursor!=null) {
				cursor.close();
				cursor=null;
			}
		}
		return obj;
	}
	/**
	 * 保留小数点后两位
	 */

	public static double convert(double value){

		long l1 = Math.round(value*100); //四舍五入
		double ret = l1/100.0; //注意：使用 100.0 而不是 100
		return ret;

	}

}
